package com.googlecode.montelin.server.dao;

import com.google.appengine.api.datastore.QueryResultIterable;
import com.google.inject.Singleton;
import com.googlecode.montelin.server.Constants;
import com.googlecode.montelin.server.domain.Address;
import com.googlecode.montelin.server.domain.Configuration;
import com.googlecode.montelin.server.domain.Page;
import com.googlecode.montelin.server.domain.User;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.util.DAOBase;

@Singleton
public class DAO extends DAOBase {

	private static DAO instance;

	static {
		ObjectifyService.register(User.class);
		ObjectifyService.register(Address.class);
		ObjectifyService.register(Page.class);
		ObjectifyService.register(Configuration.class);
	}

	public DAO() {
		super();
		instance = this;
	}
	
	public static DAO getInstance() {
		if(instance==null)
			instance = new DAO();
		return instance;
	}

	public User findUserByName(String name) {
		return ofy().find(User.class, name);
	}

	public Configuration findConfigurationByLang(String lang) {
		return ofy().find(Configuration.class, lang);
	}


	public Page findPageByCodeAndLang(String code, String lang) {
		return ofy().query(Page.class).filter("lang", lang).filter("code",code).order("position").get();
	}
	
	public QueryResultIterable<Page> findAllRootPages(String lang) {
		Page root = findPageByCodeAndLang(Constants.ROOT_CODE, lang);
		return ofy().query(Page.class).filter("parent",root).order("position").fetch();
	}
	
	public <T> T persist(T obj) {
		Key<T> key = ofy().put(obj);
		return ofy().find(key);
	}

}
